package com.hxzy.controller.api.system;

import com.hxzy.common.vo.CodeEnum;
import com.hxzy.common.vo.R;
import com.hxzy.dto.system.RoleSaveDTO;
import com.hxzy.dto.system.SysRoleDTO;
import com.hxzy.entity.system.SysRole;
import com.hxzy.service.system.SysMenuService;
import com.hxzy.service.system.SysRoleService;
import com.hxzy.vo.system.HxzyUser;
import com.hxzy.vo.system.RoleVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api")
public class SysRoleCtroller {
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @PostMapping(value = "/sysrole/list")
    public R searchByPage(@RequestBody SysRoleDTO sysRoleDTO){
        return R.success(sysRoleService.search(sysRoleDTO));
    }

    @PostMapping(value = "/sysrole/delete")
    public R delete(@RequestBody Long[] ids){
        return R.success(sysRoleService.removeBatchByIds(Arrays.asList(ids)));
    }



    @ApiOperation(value = "新增角色")
    @PostMapping(value = "/sysrole/add")
    public R add(@Valid @RequestBody RoleSaveDTO roleSaveDTO){
        this.sysRoleService.add(roleSaveDTO);
        return R.success();
    }

    @ApiOperation(value = "修改角色")
    @PostMapping(value = "/sysrole/edit")
    public R edit(@Valid @RequestBody RoleSaveDTO roleSaveDTO){
        this.sysRoleService.edit(roleSaveDTO);
        return R.success();
    }



    @ApiOperation(value = "查询ID查询角色信息有所拥有菜单权限")
    @GetMapping(value = "/sysrole/{id}")
    public R findOne(@PathVariable(value = "id") Long id){
        SysRole dbRole = this.sysRoleService.getById(id);
        if(Objects.isNull(dbRole)){
            return R.failed(CodeEnum.EDIT_DATA_NOT_FOUND);
        }

        RoleVO  roleVO=new RoleVO();
        BeanUtils.copyProperties(dbRole,roleVO);

        //查询角色拥有的菜单
        roleVO.setOwernMenus( this.sysMenuService.selectMenuTreeByUserIdOwner(id));

        return R.success(roleVO);
    }

    @ApiOperation(value = "查询角色名称是否存在")
    @PostMapping(value = "/sysrole/existsRoleName")
    public R existsRoleName(@RequestBody SysRoleDTO sysRoleDTO){
        return R.success(sysRoleService.getByRoleName(sysRoleDTO)==null?false:true);
    }

    @ApiOperation(value = "查询角色权限字符是否存在")
    @PostMapping(value = "/sysrole/existsRoleKey")
    public R existsRoleKey(@RequestBody SysRoleDTO sysRoleDTO){
        return R.success(sysRoleService.getByRoleKey(sysRoleDTO)==null?false:true);
    }

}
